package com.toune.villager.fragment

import android.annotation.SuppressLint
import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Message
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.SimpleTarget
import com.toune.villager.R
import com.toune.villager.activity.MainActivity
import com.toune.villager.activity.ShopDetailActivity
import com.toune.villager.adapter.HomeGridMenuAdapter
import com.toune.villager.bean.HomeGridMenuBean
import com.toune.villager.model.HomeFragmentModel
import com.toune.dltools.DLTimeUtil
import com.toune.dltools.adapter.DLAdapterTool
import com.toune.dltools.ui.DLBaseFragment
import com.toune.dltools.ui.DLWebActivity
import com.toune.villager.activity.BookActivity
import com.toune.villager.adapter.CommunityAdapter
import com.toune.villager.bean.BaiduHotTopicBean
import kotlinx.android.synthetic.main.fragment_home.*
import org.jsoup.Jsoup


class HomeFragment : DLBaseFragment<HomeFragmentModel>() {
    override val layout: Int
        get() = R.layout.fragment_home

    override fun lazyInit() {
        setHomeGridMenu()
        setTopRv()
        timeHelloTv.text = DLTimeUtil.helloFromTime
        runTv.text = "请自觉遵守村民公约，争做良好村民，为咱们村的美好形象做成一份力所能及的贡献。"

        getBaiduHotTopic()

        swipeRefreshLv.setOnRefreshListener {
            datas.clear()
            getBaiduHotTopic()
        }
    }

    val baiduHotTopicUrl = "https://top.baidu.com/board?tab=realtime"
    val datas: MutableList<BaiduHotTopicBean> = ArrayList()
    private fun getBaiduHotTopic() {
        Thread {
            val doc = Jsoup.connect(baiduHotTopicUrl).get().body()
            val elementsByClass = doc.getElementsByClass("category-wrap_iQLoo horizontal_1eKyQ")
            for (c in elementsByClass) {
                val url = c.getElementsByTag("a").attr("href")
                val src = c.getElementsByTag("img").attr("src")
                val title = c.getElementsByClass("c-single-text-ellipsis")[0].text()
                val sub =
                    c.getElementsByClass("content_1YWBm")[0].allElements[0].text()
                val baiduHotTopicBean = BaiduHotTopicBean()
                baiduHotTopicBean.src = src
                baiduHotTopicBean.sub = sub
                baiduHotTopicBean.title = title
                baiduHotTopicBean.url = url
                datas.add(baiduHotTopicBean)
            }
            handler.sendEmptyMessage(0)
        }.start()
    }

    lateinit var dlAdapterTool: DLAdapterTool<BaiduHotTopicBean>
    val handler = @SuppressLint("HandlerLeak")
    object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            swipeRefreshLv.isRefreshing = false
            if (this@HomeFragment::dlAdapterTool.isInitialized) {
                dlAdapterTool.notifyAdapter()
            } else {
                dlAdapterTool = DLAdapterTool<BaiduHotTopicBean>(
                    requireContext(),
                    rcy_view,
                    CommunityAdapter(R.layout.adapter_community, datas)
                )
                dlAdapterTool.getAdapter()!!.setOnItemClickListener { adapter, view, position ->
                    val bundle = Bundle()
                    bundle.putString("title", datas[position].title)
                    bundle.putString("url", datas[position].url)
                    startToActivity(DLWebActivity::class.java, bundle)
                }
            }
        }
    }

    val gridMenuDatas: MutableList<HomeGridMenuBean> = ArrayList()
    private fun setHomeGridMenu() {
        gridMenuDatas.add(
            HomeGridMenuBean(
                R.drawable.ic_community,
                "种子",
                ShopDetailActivity::class.java, 0
            )
        )
        gridMenuDatas.add(
            HomeGridMenuBean(
                R.drawable.ic_book,
                "书城",
                BookActivity::class.java, 1
            )
        )
        val homeGridMenuAdapter =
            HomeGridMenuAdapter(R.layout.adapter_home_grid_menu, gridMenuDatas)
        val dlAdapterTool =
            DLAdapterTool<HomeGridMenuBean>(requireContext(), gridRclView, homeGridMenuAdapter, 4)
        dlAdapterTool.getAdapter()!!.setOnItemClickListener { adapter, view, position ->
            startToActivity(gridMenuDatas[position].clz)
        }
    }

    private fun setTopRv() {
        var requestOptions = RequestOptions()
        requestOptions.placeholder(R.mipmap.bg_home1)
        requestOptions.error(R.mipmap.bg_home1)
        requestOptions.diskCacheStrategy(DiskCacheStrategy.NONE)
        val target = object : SimpleTarget<Drawable>() {
            override fun onResourceReady(
                resource: Drawable,
                transition: com.bumptech.glide.request.transition.Transition<in Drawable>?
            ) {
                topRv.setBackgroundDrawable(resource)
            }
        }
        val url =
            "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fbpic.588ku.com%2Fback_pic%2F05%2F69%2F20%2F815b90de14d86a3.jpg&refer=http%3A%2F%2Fbpic.588ku.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1635063353&t=ab64f7a69e7231de2314fe280130c9e6"
        Glide.with(requireContext()).load(url).apply(requestOptions).into(target)
    }
}